package com.coisini.controller.user;

import com.coisini.constant.JwtClaimsConstant;
import com.coisini.dto.UserLoginDTO;
import com.coisini.entity.User;
import com.coisini.properties.JwtProperties;
import com.coisini.result.Result;
import com.coisini.service.UserService;
import com.coisini.utils.JwtUtil;
import com.coisini.vo.UserLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@Api(tags = "C端用户相关接口")
@RequestMapping("/user/user") //第一个user表示用户端，第二个表示用户
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private  JwtProperties jwtProperties;

    /**
     * 用户登录
     * 并生成jwt令牌
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO){
        log.info("用户登录，code为：{}",userLoginDTO.getCode());
        User user =userService.login(userLoginDTO);

        //生成jwt令牌
        Map<String, Object> claims=new HashMap<>();
        //将用户id放入
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getId())
                .token(token)
                .openid(user.getOpenid())
                .build();
        return Result.success(userLoginVO);
    }


}
